/* eslint-disable react/no-unused-state */
import { AtGrid, AtTabs } from 'taro-ui'
import { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, ScrollView } from '@tarojs/components'
import { getCategoryByCity } from '@/api/category'
import tipsImg from '@/utils/global'
import { debounce } from '@/utils'
import navigationTo from '@/utils/command'
import classnames from 'classnames'
import SkeletonView from './skeleton'
import { connect } from 'react-redux'
// import { $ } from '@tarojs/extend'
import './index.scss'

interface ChildCategories {
  categoryName: string
  id: number
  parentId: number
  services: {
    frontCategoryId: number
    id: number
    name: string
    sortOrder: number
    thumbId: number
    thumbUrl: string
  }
  sortOrder: number

}

interface TabList {
  categoryName: string
  id: string
  childCategories: ChildCategories
}
interface State {
  current: number
  tabList: any,
  listLoaded: boolean
  scrollTop: number
  isScroll: boolean
  float: boolean
	scrollIntoView:string
}
@connect<any>(({ location }) => ({
  cityLocation: location.cityLocation
}))
export default class Index extends Component {
  constructor (props) {
    super(props)
    this.state = {
      current: 0,
      tabList: [],
      listLoaded: false,// 是否有数据
      scrollTop: 0,
      isScroll: false,// 是否触发 监听页面滑动
      float: true,// 用来刷新state,触发render更新
			scrollIntoView:''
    }
  }
  state: State

  UNSAFE_componentWillMount() { }

  componentDidMount() {
      this.setState({
        current: 0,
        tabList: [],
        listLoaded: false,// 是否有数据
        scrollTop: 0,
        isScroll: false,// 是否触发 监听页面滑动
        float: true,// 用来刷新state,触发render更新
      }, () => {
				console.log
        this.getTabList()
      })

  }

  componentWillUnmount() { }

  componentDidShow() {

  }

  componentDidHide() { }

  // 点击左边导航栏
  handleTab(idx) {
    const { tabList, float } = this.state
		let id = tabList[idx].id
    this.setState({
      float: !float,
      current: idx,
      isScroll: true,//阻止 触发页面滑动逻辑
			scrollIntoView:`a-${id}`
    })
  }

  // 获取列表接口
  getTabList() {
    getCategoryByCity().then(res => {
      const { data, success } = res.data
      if (success) {
        const list = data.map((v) => {
          v['title'] = v.categoryName
          return v
        })
        this.setState({
          tabList: list,
          listLoaded: true,
        })
      }

    })
  }

	 // 监听页面滑动
	 scrollPage = debounce((e) => {
    const { scrollTop } = e.target
    const { tabList, isScroll } = this.state
    if (!(tabList && tabList.length > 1)) return
    const { windowHeight } = Taro.getSystemInfoSync()
    if (isScroll) {
      this.setState({
        isScroll: false,
      })
    } else {
      const length = tabList.length
			console.log('tabList',tabList)
      const list = tabList.map((val, idx) => {
        if (idx >= length - 2) {
          return Number(val.offsetTop) - Math.floor((Number(windowHeight) / (tabList.length)) * idx)
        } else {
          return Number(val.offsetTop) - Number(windowHeight / 3)
        }

      })
      const re = this.getIndexToIns(list, scrollTop)
			console.log('re',re)
      this.setState({
        current: re == 0 ? re : re - 1,
        isScroll: false,
      })

    }
  }, 10)

  getIndexToIns(arr, num) {
    return arr.concat(num).sort((a, b) => a - b).lastIndexOf(num);
  }



  render() {
    const {
      tabList,
      listLoaded,
      current,
			scrollIntoView
    } = this.state
		console.log('listLoaded',listLoaded)
		console.log('tabList',tabList)
		console.log('scrollIntoView',scrollIntoView)
    return listLoaded ? (
			<View style='height:100vh' className='category-main'>
				<ScrollView
						scrollWithAnimation={process.env.TARO_ENV === 'weapp' ? true : false}
						scrollY={true}
						// onScroll={this.scrollPage.bind(this)}
						scrollIntoView={scrollIntoView}
						className='index-list'>
						<View className='category-tabs'>
							<AtTabs
								current={current}
								scroll
								height={"100%"}
								tabDirection='vertical'
								tabList={tabList}
								onClick={this.handleTab.bind(this)}></AtTabs>
						</View>

						<View  className='category-content'>
							<View className='category-cont'>
								{
									tabList && tabList.length > 0 && tabList.map((v, i) => {
										return (
											<View id={`a-${v.id}`} key={v.id} className={classnames(i === current && 'act')}>
												{
													v.childCategories && v.childCategories.length > 0 && v.childCategories.map((child, idx) => {
														return (
															<View key={child.id} className={`category-cont--li ${idx == 0 ? 'goods-list' : ''} `}>
																<View className='category-title'>{child.categoryName}{i.id}</View>
																<AtGrid className='category-block' onClick={(item) => navigationTo(item.command)} hasBorder={false} data={child.services.map(item => {
																	return {
																		value: item.name,
																		image: item.thumbUrl || tipsImg,
																		id: item.id,
																		command: item.command
																	}
																})}
																/>
															</View>
														)
													})
												}
											</View>
										)
									})
								}
							</View>
						</View>
				</ScrollView>
			</View>
      ) : <SkeletonView />
  }
}
